package com.dfd.store.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.connector.Request;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;

import com.dfd.store.domain.Category;
import com.dfd.store.domain.User;
import com.dfd.store.service.CategoryService;
import com.dfd.store.service.UserService;
import com.dfd.store.service.impl.CategoryServiceImpl;
import com.dfd.store.service.impl.UserServiceImpl;
import com.dfd.store.utils.MailUtils;
import com.dfd.store.utils.MyBeanUtils;
import com.dfd.store.utils.UUIDUtils;
import com.dfd.store.web.base.BaseServlet;

public class UserServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;

    /**
     * 注册页面
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     * @throws Exception
     */
    public String registUI(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, Exception {

        return "/jsp/register.jsp";
    }

    /**
     * 登录页面
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     * @throws Exception
     */
    public String loginUI(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, Exception {

        return "/jsp/login.jsp";
    }

    /**
     * 用户注册
     * 
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String userRegist(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 接收表单参数
        Map<String, String[]> map = request.getParameterMap();
        // 通过反射将map中的数据放到对象
        User user = new User();
        MyBeanUtils.populate(user, map);
        user.setUid(UUIDUtils.getId());
        user.setState(0);
        user.setCode(UUIDUtils.getCode());
        System.out.println(user);
        // // 遍历map中的数据
        // Set<String> keySet = map.keySet();
        // Iterator<String> iterator = keySet.iterator();
        // while (iterator.hasNext()) {
        // String str = iterator.next();
        // System.out.println(str);
        // String[] strs = map.get(str);
        // for (String string : strs) {
        // System.out.println(string);
        // }
        // System.out.println();
        // }
        // 调用业务层注册功能
        UserService userService = new UserServiceImpl();
        try {
            userService.userRigist(user);
            // 注册成功,向用户邮箱发送信息,跳转到提示页面
            // 发送邮件
            MailUtils.sendMail(user.getEmail(), user.getCode());
            request.setAttribute("msg", "用户注册成功,请激活");
        } catch (Exception e) {

            request.setAttribute("msg", "用户注册失败,请重试");
        }
        return "/jsp/info.jsp";

    }

    /**
     * 用户激活
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String active(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取激活码
        String code = request.getParameter("code");
        // 调用业务逻辑层激活功能
        UserService userService = new UserServiceImpl();
        boolean flag = userService.userActive(code);
        if (flag == true) {
            // 用户激活成功,向request放入提示信息,转发到登录页面,
            request.setAttribute("msg", "用户激活成功,请登录");
            return "/jsp/login.jsp";
        } else {
            request.setAttribute("msg", "用户激活失败,请重新激活");
            return "/jsp/info.jsp";
        }

    }

    /**
     * 用户登录
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    // userLogin
    public String userLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取用户数据
        User user = new User();
        // 这个方法会遍历map<key, value>中的key，如果bean中有这个属性，就把这个key对应的value值赋给bean的属性。
        MyBeanUtils.populate(user, request.getParameterMap());
        Map<String, String[]> map = request.getParameterMap();

        String[] xx = (String[]) map.get("checkcode");

        String code = String.valueOf(xx[0]);
        // 调用业务逻辑层
        UserService userService = new UserServiceImpl();
        User user1 = null;
        try {
            String validatecode = (String) request.getSession().getAttribute("key");
            if (StringUtils.isNotBlank(code)) {
                if (validatecode.equals(code)) {
                    user1 = userService.userLogin(user);

                    // 用户登录成功,将用户信息放入session
                    request.getSession().setAttribute("loginUser", user1);
                    response.sendRedirect("/Store/index.jsp");
                    return null;
                } else {
                    request.getSession().setAttribute("msg", "请输入正确的验证码");
                    return "/jsp/login.jsp";
                }
            } else {
                request.getSession().setAttribute("msg", "请输入验证码");
                return "/jsp/login.jsp";
            }
            // select * from user where username =?
        } catch (Exception e) {
            // 用户登录失败了
            e.printStackTrace();
            String msg = e.getMessage();
            System.out.println(msg);
            // 向request放入失败的信息
            request.getSession().setAttribute("msg", msg);
            return "/jsp/login.jsp";
        }
    }

    /**
     * 根据key获取value
     * 
     * @param map
     * @param value
     * @return
     */
    public static Object getKey(HashMap<Object, Object> map, String v) {

        Set set = map.entrySet();

        Iterator iterator = set.iterator();

        String key = "";

        while (iterator.hasNext()) {

            Map.Entry<String, Object> enter = (Entry<String, Object>)

            iterator.next();

            if (enter.getValue().equals(v)) {

                key = enter.getKey();

            }
        }

        return key;

    }

    /**
     * 用户登出
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String userLogout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 清除session
        request.getSession().invalidate();
        // 重定向到首页
        response.sendRedirect("/Store/index.jsp");
        return null;
    }
}